package com.cunfang.util;

import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;

/**
 * 加密工具类
 * 
 * @author RXJ
 *
 */
public class MD5 {

	/**
	 * 密码加密
	 * 
	 * @param value
	 *            需要加密的字符串
	 * @return 返回32位字节的加密字符串
	 */
	public static String md5(String value) {
		MessageDigest md;
		StringBuffer sb = new StringBuffer();
		try {
			md = MessageDigest.getInstance("MD5");
			md.update(value.getBytes());
			byte[] data = md.digest();
			int index;
			for (byte b : data) {
				index = b;
				if (index < 0)
					index += 256;
				if (index < 16)
					sb.append("0");
				sb.append(Integer.toHexString(index));
			}
		} catch (NoSuchAlgorithmException e) {
			e.printStackTrace();
		}
		return sb.toString();
	}

	/**
	 * 校验密码是否正确
	 * 
	 * @param password
	 *            未经加密的密码
	 * @param ciphertext
	 *            密文
	 * @return boolean
	 */
	public static boolean toCheckPassword(String password, String ciphertext) {
		boolean result = false;
		if (password != null && !password.equals("")) {
			String value = md5(password);
			if (value.equals(ciphertext)) {
				result = true;
			}
		}
		return result;
	}

	public static void main(String args[]) {
		String ciphertext = md5("121916449@qq.com");
		System.out.println(toCheckPassword("121916449", ciphertext));

	}

}
